// cloudfunctions/login/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const axios = require('axios');
const db = cloud.database()
exports.main = async (event, context) => {
  const code = event.code;
  const appid = 'wx8a5b19e4aa3b5500';
  const secret = '084945bbf37afc298695ac2001b56275';
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
  try {
    const res = await axios.get(url);
    const openid = res.data.openid;
    const session_key = res.data.session_key;
    console.log("openid:", openid);
    console.log("session_key:", session_key);
    // 进行用户认证、数据存储等操作
    //将获取的数据存储到数据库用来判断是否是我老婆
   const et = await db.collection('users').where({
      openid: openid,
      // session_key: session_key,
    }).get()
    console.log(et);
    let id =et.data[0]._id
    let aut = et.data[0].aut
    let datebus = et.data[0].databiuse;
    let jf = et.data[0].jf;
    console.log("id:",id,"======qut:",aut);
    return {
      success: true,
      data:{id:id,aut:aut,sjk:datebus,jf:jf,user:et.data[0]},//返回id和作者
      // pd:id=='59af7b52674bc8f4011e6ea2065b8464'
    };
  } catch (err) {
    console.log('换取用户信息失败:', err);
    return {
      success: false
    };
  }











































  //     const app = await cloud.init({
  //     env: 'womenlia-2gcdym6fb861b775'
  // });
  // const c1 = new wx.cloud.Cloud({
  //   resourceEnv:'womenlia-2gcdym6fb861b775'
  // })
  // // const userinfo= await app.auth().getUserInfo()
  // // console.log(userinfo);

  //     console.log(app);
  // console.log("==================S");
  //   ///*
  //     const code = event.code;
  //     const appid = 'wx8a5b19e4aa3b5500'; // 替换为你的微信小程序AppID
  //     const secret = '084945bbf37afc298695ac2001b56275'; // 替换为你的微信小程序AppSecret
  //     console.log(code);

  //     try {
  //         // 1. 先通过微信官方接口获取openid等信息
  //         const wxResponse = await c1.getWxContext();
  //         const openid = wxResponse.openid;
  //       console.log(openid);
  //       console.log(wxResponse);
  //         // 2. 根据openid在数据库中查询用户是否已存在
  //         const db = cloud.database();
  //         const user = await db.collection('users').where({ user:openid }).findOne();

  //         if (!user) {
  //             // 如果用户不存在，创建新用户记录
  //             await db.collection('users').add({
  //                 data: {
  //                     user:openid,
  //                     nickname: wxResponse.userInfo.nickname,
  //                     avatarUrl: wxResponse.userInfo.avatarUrl
  //                 }
  //             });
  //         }

  //         // 3. 返回登录成功信息
  //         return {
  //             success: true
  //         };
  //     } catch (error) {
  //         return {
  //             success: false,
  //             message: '登录验证失败',
  //             log:error
  //         };
  //     }



  //*/
};